import { defineStore } from 'pinia'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    isAuthenticated: false,
    token: null, // 保存 JWT token
  }),
  actions: {
    async login(credentials) {
      const { email, password } = credentials
      if (!email || !password) {
        throw new Error('邮箱和密码不能为空')
      }

      try {
        // 向后端发送 POST 请求，进行登录验证
        const response = await axios.post('http://localhost:5000/api/v1/login', { email, password })
        
        // 如果登录成功，保存 JWT token
        this.token = response.data.access_token
        this.isAuthenticated = true
        this.user = { email }

        // 将 JWT token 存储在 localStorage 中，保持登录状态
        localStorage.setItem('token', this.token)

      } catch (error) {
        console.error('Login error:', error)
        throw new Error('登录失败，请检查用户名和密码')
      }
    },
    logout() {
      this.user = null
      this.isAuthenticated = false
      this.token = null

      // 清除 localStorage 中的 token
      localStorage.removeItem('token')
    },
  }
})
